(function () {

    var style = `
        body{
            margin: 0px;
            padding: 0px;
        }
        /* div {
            -moz-user-select:none;
            -webkit-user-select:none;
            user-select:none;    
        } */
        div{
            box-sizing: border-box;
        }
        
        #root.layui-fluid {
            padding: 0;
        }
        #root .layui-tab{
            margin: 0;
        }
        
        #root{
            background: #ccc;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        #root.layui-fluid {
            padding: 0;
        }
        #root .layui-tab{
            margin: 0;
        }
        
        #root .top{
            height: calc(100vh - 340px);
        }
        #root .left{
            border-right: 1px solid #e6fdf9;
        }
        #root .left,#root .right, .right .layui-card{
            height: 100%;
            background-color: #FFFFFF;
        }
        
        .console {
            height: 340px;
        }
        .console.hidden {
            height: 30px;
            overflow: hidden;
        }
        
        .console  .log{
            height: 100%;
            background: #000;
            overflow: auto;
            scroll-behavior: smooth;
            color: #ececec;
            font-size: 13px;
            padding: 5px 10px;
        }
        
        .console  .log  p{
            line-height: 18px;
            padding: 0;
            margin: 0;
        }
        
        .console .log  p > .time {
            margin-right: 5px;
            color: #489a83;
        }
        .console  .log  p.error {
            color: #ca4016;
        }
        .console  .log  p > .msg {
            white-space: nowrap;
        }
        .console .log-open-oper{
            display: inline-block;
            position: absolute;
            right: 5px;
            cursor: pointer;
        }
        .top {
            flex: 1;
            overflow: auto;
            display: flex;
            flex-direction: column;
        }
        .top .top-header{
            height: 32px;
            line-height: 30px;
            padding: 0 5px;
            background: #057768;
        }
        .top .top-body{
            flex: 1;
            overflow: auto;
            display: flex;
        }
        .top .left{
            width: 25%;
        }
        .top .right{
            flex: 1;
            overflow: auto;
        }
        .jwebui-card,
        .jwebui-table,
        .jwebui-tab{
            height: 100%;
        }
    `;

    var template = `
        <div class="top ">
            <div class="top-header">
                <a class="layui-btn layui-btn-xs layui-btn-default" @click="createTask" ><i class="layui-icon layui-icon-add-circle-fine"></i>新建</a>
                <a class="layui-btn layui-btn-xs layui-btn-default" @click="deleteTask"><i class="layui-icon layui-icon-delete"></i>删除</a>
                <a class="layui-btn layui-btn-xs layui-btn-default" @click="refresh"><i class="layui-icon layui-icon-refresh"></i>显示所有数据</a>
                <a class="layui-btn layui-btn-xs layui-btn-default" @click="openCronJob"><i class="layui-icon layui-icon-time"></i>查看定时记录</a>
            </div>
            <div class="top-body">
                <div class="left">
                    <jwebui-card title="任务列表">
                        <jwebui-table :cols="taskCols" :data="taskList" @clickrow="clickTask">
                            <template v-slot:#task_name="slotProps">
                                <span>任务名称 </span>
                            </template>
                            <template v-slot:task_status="slotProps">
                                <span :style="'color:'+status[slotProps.data.task_status].color">{{ status[slotProps.data.task_status].title }}{{slotProps.data.task_status == 3?'('+currProcess+'%)':''}}</span>
                            </template>
                            <template v-slot:task_oper="slotProps">
                                <span :style="'color:'+status[slotProps.data.task_status].color"><i title="执行当前任务" :class="'layui-icon oper_icon ' + getOperIconClass(slotProps.data.task_status)" @click.stop="taskAction(slotProps.data)"></i></span>
                            </template>
                            <template v-slot:#task_oper="slotProps">
                                <span ><i :class="'layui-icon oper_icon layui-icon-play'" title="执行全部任务" @click.stop="taskActionAll('start')"></i></span>
                            </template>
                        </jwebui-table>
                    </jwebui-card>
                </div>
                <div class="right">
                    <jwebui-card :title="currTask.task_name?'任务 《' + currTask.task_name + '》':'--------'">
                        <jwebui-tab :tabs="tabs" :active="activeTabKey" @tabchange="activeChange">
                            <template v-slot:data="slotProps">
                                <task-data ref="taskDataRef" :refresh="refreshRecordList" :task="currTask"></task-data>
                            </template>
                            <template v-slot:config="slotProps">
                                <task-config :task="currTask" @save-success="saveConfigCallback"></task-config>
                            </template>
                        </jwebui-tab>
                    </jwebui-card>
                </div>
            </div>
        </div>
        <div :class="logShow?'console':'console hidden'">
            <jwebui-card>
                <template v-slot:header>
                    <div>
                        <span>调试：</span>
                        <button type="button" @click.stop="switchSpiderWindow" class="layui-btn layui-btn-xs">显示隐藏采集窗口</button>
                        <button type="button" @click.stop="toggleDevTools" class="layui-btn layui-btn-xs">显示隐藏开发者工具</button>
                        <button type="button" @click.stop="clearLog" class="layui-btn layui-btn-xs">清空日志</button>
                        <button type="button" @click.stop="debugChecked=!debugChecked" class="layui-btn layui-btn-xs">
                            <input type="checkbox" style="vertical-align: text-top;" v-model="debugChecked" name="showDebugLog"  >显示DEBUG信息
                        </button>
                        <div class="log-open-oper" @click="logShow=!logShow">{{logShow?'收缩日志':'展开日志'}}</div>
                    </div>
                </template>
                <div id="logArea" class="log" v-if="logShow"></div>
            </jwebui-card>
        </div>
        <jwebui-model title="定时任务运行记录" :show="cronJobModel" @close="cronJobModel=false" width="800px" height="500px">
            <cron-job></cron-job>
        </jwebui-model>
    `

    var component = {
        data() {
            return {
                logShow: true,
                activeTabKey: 'data',
                cronJobModel: false,
                debugChecked: false,
                taskList: [],
                currTask: {},
                taskEvent: {},
                currProcess: 0,
                refreshTaskList: 1,
                refreshRecordList: 1,
                status: {
                    '0': { title: '未开始', color: '#ccc' },
                    '1': { title: '准备采集', color: '#99aa99' },
                    '2': { title: '等待执行', color: '#99ee99' },
                    '3': { title: '正在进行', color: '#77aa77' },
                    '4': { title: '任务异常', color: '#aa6666' },
                    '5': { title: '任务结束', color: '#ccc' },
                    '6': { title: '正在停止', color: '#ccc' },
                    '7': { title: '已停止', color: '#ccc' },
                }
            }
        },
        mounted: function () {
            this.init();
            this.loadTaskData();
            this.initTaskEventListener();
        },
        updated: function () {
        },
        computed: {
            taskCols() {
                var cols = [
                    { title: '任务名称', key: 'task_name', width: '*' },
                    { title: '状态', key: 'task_status', width: '120px' },
                    { title: '操作', key: 'task_oper', width: '40px' },
                ]
                return cols;
            },
            tabs() {
                return [
                    { key: 'data', title: this.currTask.task_id ? '任务数据' : '所有任务数据' },
                    { key: 'config', title: this.currTask.task_id ? '任务配置' : '新建任务' },
                ];
            },
        },
        watch: {
            taskEvent: function (val) {
                this.loadTaskData();
            }
        },
        methods: {
            init: function() {
                var that = this;
                ipcRenderer.on("log", function (event, { msg, type }) {
                    var logArea = document.getElementById("logArea");
                    if(!logArea) return;
                    var children = logArea.children;
                    var log = null;
                    msg = that.htmlEncode(msg.substring(0, 1000));
                    switch (type) {
                        case 'debug':
                            log = `<p class='debug'>[调试] <span class="time">${new Date().Format("yyyy-MM-dd HH:mm:ss")}</span> <span class="msg"> ${msg}</span></p>`;
                            break;
                        case 'error':
                            log = `<p class='error'>[错误] <span class="time">${new Date().Format("yyyy-MM-dd HH:mm:ss")}</span> <span class="msg"> ${msg}</span></p>`;
                            break;
                        default:
                            log = `<p class="info">[信息] <span class="time">${new Date().Format("yyyy-MM-dd HH:mm:ss")}</span> <span class="msg"> ${msg}</span></p>`;
                    }
        
                    if (type == 'debug' && !that.debugChecked) {
                        // do nothing
                    } else {
                        logArea.innerHTML = logArea.innerHTML + log;
                        logArea.children[logArea.children.length - 1].scrollIntoView()
                        if (logArea.children.length > 500) {
                            logArea.children[0].remove();
                        }
                    }
                    that.saveLogLine(that.getText(log));
                })
            },
            toggleDevTools() {
                var result = ipcRenderer.sendSync('toggleDevTools');
            },
            getText(html) {
                var a = document.createElement("div");
                a.innerHTML = html;
                return a.innerText
            },
            htmlEncode(html) {
                var temp = document.createElement("div");
                (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
                var output = temp.innerHTML;
                temp = null;
                return output;
            },
            saveLogLine(logLine) {
                if (logLine) {
                    var logDir = process.cwd() + "/log";
                    if (!fs.existsSync(logDir)) {
                        fs.mkdirSync(logDir, { recursive: true });
                    }
                    if (countLine > maxLogLineNum) {
                        fs.renameSync(logDir + '/log.txt', logDir + '/log.' + (new Date().Format('yyyyMMddHHmmss')) + '.txt');
                        countLine = 0;
                    }
                    fs.appendFileSync(logDir + '/log.txt', logLine + "\r\n", { encoding: 'utf-8' });
                    countLine = countLine + 1;
                }
            },
            clearLog: function () {
                document.getElementById("logArea").innerHTML = "";
            },
            switchSpiderWindow: function () {
                ipcRenderer.send("switchSpiderWindow");
            },
            activeChange: function (key) {
                this.activeTabKey = key;
            },
            openCronJob: function () {
                this.cronJobModel = true;
            },
            deleteTask: function () {
                if (this.currTask.task_id) {
                    var that = this;
                    layer.confirm('确定要删除任务《' + that.currTask.task_name + '》吗？', { icon: 3, title: '提醒' }, function (index) {
                        var result = ipcRenderer.sendSync("deleteTask", that.currTask.task_id);
                        if (result.success) {
                            layui.layer.msg("删除任务【" + that.currTask.task_name + "】成功！")
                            that.loadTaskData();
                            that.currTask = {};
                        } else {
                            layui.layer.alert("删除任务【" + that.currTask.task_name + "】失败！" + result.error);
                        }

                        layer.close(index);
                    });
                } else {
                    layui.layer.alert("请选择一个要删除的任务！");
                }
            },
            createTask: function () {
                this.currTask = {};
                this.activeTabKey = "config"
            },
            refresh: function () {
                this.currTask = {};
                this.activeTabKey = "data"
            },
            saveConfigCallback: function (data) {
                this.loadTaskData();
                this.reloadCurrTask(data);
            },
            reloadCurrTask: function (data) {
                for (let index = 0; index < this.taskList.length; index++) {
                    const task = this.taskList[index];
                    if (task.task_id == data.task_id) {
                        this.currTask = task;
                        break;
                    }
                }
            },
            loadTaskData: function () {
                this.taskList = ipcRenderer.sendSync("loadTaskList")
            },
            clickTask: function (task) {
                this.currTask = task;
                // layui.element.tabChange("right_tab_page", "data_page");
                return false;
            },
            taskActionAll: function (oper) {
                var result = ipcRenderer.sendSync("taskActionAll", { oper: oper })
                if (result.success) {
                    this.loadTaskData();
                } else {
                    if (oper == 'start') {
                        showLog("开始操作失败！" + result.error);
                    } else if (oper == 'stop') {
                        showLog("停止任务操作失败！" + result.error);
                    }
                }
                return false;
            },
            taskAction: function (task) {
                var oper = '';
                switch (task.task_status) {
                    case 0:
                    case 4:
                    case 5:
                    case 7:
                        oper = 'start';
                        break;
                    case 1:
                    case 2:
                    case 3:
                        oper = 'stop';
                        break;
                    default:
                        oper = 'stop';
                }
                if (oper) {
                    var taskObject = JSON.parse(JSON.stringify(task));
                    var result = ipcRenderer.sendSync("taskAction", { task: taskObject, oper: oper })
                    if (result.success) {
                        this.loadTaskData();
                    } else {
                        if (oper == 'start') {
                            showLog("开始操作失败！" + result.error);
                        } else if (oper == 'stop') {
                            showLog("停止任务操作失败！" + result.error);
                        }
                    }
                }
                return false;
            },
            getOperIconClass: function (taskStatus) {
                var className = '';
                switch (taskStatus) {
                    case 0:
                    case 4:
                    case 5:
                    case 7:
                        className = 'layui-icon-play';
                        break;
                    case 1:
                    case 2:
                    case 3:
                        className = 'layui-icon-pause';
                        break;
                    default:
                        className = 'layui-icon-pause';
                }
                return className;
            },
            initTaskEventListener: function () {
                var that = this;
                ipcRenderer.on("task_event", function (event, args) {
                    if (args.process != undefined) {
                        that.currProcess = args.process;
                    }
                    if (args.type == "run" && (args.setup == 'spiderUrls' || args.setup == 'spiderContent')) {
                        // 刷新采集记录列表
                        that.$refs.taskDataRef.$forceUpdate()
                        that.refreshRecordList = new Date().getTime();
                    } else {
                        // 刷新任务列表状态
                        that.loadTaskData();
                    }
                })
            }
        },
        template: template,
    }

    component.style = style;

    return component;
})()